<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/3 0003
 * Time: 14:55
 */

namespace app\api\controller;

header("Content-Type: text/html;charset=utf-8");

use app\api\service\Token;
use app\lib\dadaapi\ToolsInco;
use app\common\model\Dadareasons;
use app\common\model\Product;
use app\common\model\Productspecgroups;
use app\common\model\User;
use controller\DadaAddOrder;


class ShoppingCar extends BaseController
{



    /*
    * 获取个人购物车列表
    */
    public function getMyShopingCars()
    {
        $param = self::getHttpParam();
        $tools = new ToolsInco();
        $param = $tools->inco($param);




     //   $newData=iconv("ASCII","utf-8", json_encode($param));
    /*    $encode = mb_detect_encoding(json_encode($param), array("utf-8"));
        print_r($encode);exit;*/


        $shoppingCarModel = new \app\common\model\Shoppingcar();
        $token = new Token();
        $uid = $token->getCurrentUid();
     //   $uid = $param->userId;

        if(!isset($param->page)){
            $param->page = 0;
        }

        if(!isset($param->limit)){
            $param->limit = 15;
        }

        if($uid && $uid!=null){
            $whereOption = array(
                "userId"=>$uid,
                "storeId"=>$param->storeId,
                "status"=>$shoppingCarModel::STATUS_VALID,
            );
            $resultList = $shoppingCarModel->select_all($whereOption,$param->page,$param->limit);

            if($resultList['list']&&!empty($resultList)){
                foreach($resultList['list'] as $item){
                    if(isset($item->product) && $item->product!=null){
                       // $item->oldPrice = $item->product->currentPrice;
                        $item->product;
                        if(isset($item->Productspecgroups) && !empty($item->Productspecgroups)){
                            $item->Productspecgroups;
                         //   $item->oldPrice = $item->Productspecgroups->currentPrice;
                        }
                    }else{
                        //修改状态为删除
                        $shoppingCarModel->delProduct($param->productId,$uid);
                    }
                }
            }
            return show(config('status.SUCCESS_STATUS'),self::MSG_SUCCESS,$resultList);
        }else{
            return show(config('status.ERROR_STATUS'),self::NOT_DATA,$uid);
        }

    }


    /**
     * @return \think\response\Json
     * 添加 和 修改 购物车
     */
    public function add_or_update_shoppingCar()
    {
        $param = self::getHttpParam();
        $tools = new ToolsInco();


        $token = new Token();
        $uid = $token->getCurrentUid();


        // $uid = $param->userId;
        if (!$uid && $uid == null) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, $uid);
        }

        $userModel = new User();

        $shoppingModel = new \app\common\model\Shoppingcar();

        $userId = $uid;


        $productId = $param->productId;


        $productModel = new Product();

        $product = $productModel->getProduct($param);

        if ($userId == "" || $userId == null) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, array('userId' => $userId));
        }
        if ($productId == "" || $productId == null) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, array('productId' => $productId));
        }
        $currentUser = $userModel->findCurrentUser($userId);
        if (!$currentUser && empty($currentUser)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, array('userId' => $userId));
        }
        if ($param->storeId == "" || $param->storeId == null) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, array('storeId' => $param->storeId));
        }

        if (isset($param->specId) && $param->specId != "") {
            $data['specId'] = $param->specId;  //规格id   1，2，3
            //根据规格id获取商品价格
            $productSpecGroupsModel = new Productspecgroups();
            $Spec = $productSpecGroupsModel->getSpec($param->specId);
            //相同商品用户  不同规格查询
            $currentShoppingCar = $shoppingModel->getCurrentShoppingcarSpec($productId, $userId, $param->specId);
            $data['oldPrice'] = $Spec['currentPrice'];            //商品价格
            if($Spec['isStore'] == 1){
                if($Spec['storeCount']<=0){
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, "当前商品库存不足！计入失败。");
                }

            }

            if( $Spec['limitCount'] > 0 && ($Spec['limitCount'] <    $param->count)){
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, "当前购买数量大于限购数量");
            }

        } else {
            $currentShoppingCar = $shoppingModel->getCurrentShoppingcar($productId, $userId);
            $data['specId'] = "";  //规格id   1，2，3
            $data['oldPrice'] = $product['currentPrice'];            //商品价格
            if($product['isStore'] == 1){
                if($product['storeCount']<=0){
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, "当前商品库存不足！计入失败。");
                }
            }


            if( $product['limitCount'] > 0 && ($product['limitCount'] < $param->count)){
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, "当前购买数量大于限购数量");
            }

        }
        if (isset($param->count) && $param->count != "") {
            $data['count'] = $param->count;  //规格id   1:2:3
        } else {
            $data['count'] = 0;
        }
        $data['creatDate'] = date('Y-m-d h:i:s', time());           //创建时间
        $data['productId'] = $productId;      //商品id
        $data['userId'] = $userId;            //当前用户id
        $data['status'] = $shoppingModel::STATUS_VALID;            //状态有效
        $data['storeId'] = $param->storeId;                 //店铺id
        if ($currentShoppingCar && !empty($currentShoppingCar)) {
            $data['updateDate'] = date('y-m-d h:i:s', time());//规格id   1:2:3
            if (isset($currentShoppingCar->id)) {
                $data['id'] = $currentShoppingCar->id;
            } else {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, "商品id不能为空");
            }
            if ($data['count'] <= 0) {
                $data['status'] = $shoppingModel::STATUS_DELETE;            //状态有效
            }
            $result = $shoppingModel->updateMyShoppingCar($data);
        } else {
            $data['id'] = get_uniqid_id();
            if ($data['count'] <= 0) {
                $data['status'] = $shoppingModel::STATUS_DELETE;            //状态有效
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, "count不能为0");
            }
            $result = $shoppingModel->addMyShoppingCar($data);
        }
        if ($result) {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
        } else {
            // return show(config('status.ERROR_STATUS'), self::NOT_PARAM, $result);
        }
    }

    /**
     * 删除商品
     */
    public function delShoppingCar()
    {
        $param = self::getHttpParam();
        $token = new Token();
        $uid = $token->getCurrentUid();



        // $uid = $param->userId;
        if (!$uid && $uid == null) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, $uid);
        }
        $ShoppingcarModel = new \app\common\model\Shoppingcar();
        $productModel = new Product();
        $shoppingCarIds = $param->shoppingCarId;
        if (isset($param->is_del) && $param->is_del) {
            if ($shoppingCarIds && $shoppingCarIds != null) {
                $result = $ShoppingcarModel->delAll($shoppingCarIds, $uid);
                if ($result) {
                    return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, "批量删除成功");
                } else {
                    return show(config('status.ERROR_STATUS'), self::MSG_SUCCESS, "批量删除失败");
                }
            } else {
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, "productid为空");
            }
        } else {

            if ($ShoppingcarModel->delProduct($shoppingCarIds, $uid)) {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, "删除成功");
            } else {
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, "删除失败");
            }
        }
    }


/* 达达订单取消理由存入数据库
    public function reasons(){
       $dadaAddOrder = new \distribution\DadaAddOrder();
       $reasonResult = $dadaAddOrder->reasons();
       $result = $reasonResult['result'];
       $dadaReasonsModel = new Dadareasons();
       $dadaReasonsModel->insertDadaReasons($result);

    }*/






}